package web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import model.*;
import java.util.*;

/*****************************************************************
First time: Store the data in JavaBean. Generate gender request!
Second time: Retrieve the data, generate final future information.
*****************************************************************/
public class SimpleHoroscopeServlet extends HttpServlet{
	
	public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException{
		
		//1.1 Prepare the javabean to store
		PersonalDetailsBean db;
		String name;
		int Zodiac;
		boolean gender;
		String future="";
		HttpSession session = req.getSession();
		String[] futurePool = {"You will have a long life",
				"You will have a rich life",
				"You will find a tall handsome stranger",
				"You will have six children"};
		
		//1.2 Prepare the writer
		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		
		if(session.isNew()) {
			//2.1 Store in Javabean
			db = new PersonalDetailsBean();
			name = req.getParameter("name");
			Zodiac = Integer.parseInt(req.getParameter("Zodiac"));
			db.setName(name);
			db.setZodiac(Zodiac);
			session.setAttribute("Info",db);
			
			//3.1 Generate the html response
			out.println("<html><body>\n");
			out.println("<h2> Please input your gender! </h2>\n");
			out.println("<form method=\"post\">");
			out.println("Gender:<br>");
			out.println("<input type=\"radio\" name =\"gender\" value=\"true\">Male<br>\n");
			out.println("<input type=\"radio\" name =\"gender\" value=\"false\">Female<br>\n");
			out.println("<input type=\"submit\" value=\"submit\">\n");
			out.println("</form>");
			out.println("</body></html>");
		}
		else {
			//2.2 Retrieve in JavaBean
			db = (PersonalDetailsBean) session.getAttribute("Info");
			if(req.getParameter("gender")!=null){
			gender = Boolean.valueOf(req.getParameter("gender"));
			db.setGender(gender);
			}
			else
			gender = db.isGender();
			
			name = db.getName();
			Zodiac = db.getZodiac();
			session.setAttribute("Info",db);
			
			//TODO future gen
			if(gender && Zodiac<=6)
			future = futurePool[0];
			else if(gender && Zodiac>6)
			future = futurePool[1];
			else if(!gender && Zodiac<=6)
			future = futurePool[2];
			else if(!gender && Zodiac>6)
			future = futurePool[3];
			
			//3.2 Generate the html response
			out.println("<html><body>\n");
			out.println(name + ", " + future);
			out.println("</body></html>");			
		}
		
	}
}